﻿using System;
using System.Collections.Generic;
using System.Text;
using T.FAS.Runtime.Action.SPI;
using T.FAS.Runtime.Base.Entity;
using  T.ServiceFramework.ServiceGateway.Client;
using  T.ServiceFramework.ServiceGateway.ClientExtension;
using T.ServiceComponent.Config.Client;
using Newtonsoft.Json;

namespace T.FAS.Runtime.Action.Engine
{
    public class RemoteInvokeEngine : IActionExecuteProxy
    {
        private const string FASDomianUrl = "FAS.FASDomainUrl";
        private string GetCurDomain()
        {
            return ConfigManager.GetConfigValue(FASDomianUrl);
        }

        public object Execute(ActionExecContext context)
        {
            var parameters = GetServiceParams(context);
            return RemoteInvoke(context.ActionPlugin.RemoteInvokeSID,parameters);
        }

        private Dictionary<string,string> GetServiceParams(ActionExecContext context)
        {
            switch (context.ActionPlugin.MetaTypeID.ToLower())
            {
                case "approveflow":
                    return AFServiceParamsBuilder(context);
                default:
                    return new Dictionary<string, string>();
            }
        }
        private Dictionary<string, string> AFServiceParamsBuilder(ActionExecContext context)
        { 
            Dictionary<string,string> paramDic = new Dictionary<string, string>();
            paramDic.Add("metaId",context.MetadataID);
            paramDic.Add("actionCode",context.ActionCode);
            paramDic.Add("parameters",JsonConvert.SerializeObject(context.RemoteInvokeParameter));
            return paramDic;

        }
        private TResult RemoteInvoke(string serviceID,Dictionary<string,string> parameters)
        {
            var client = new SGHttpClient(false);
            var result = client.PostRequestDirect<TResult>(GetCurDomain(),serviceID,parameters);
            return result.data;

        }

        public object ExecuteWithSubEngine(IActionExecuteEngine subEngine, ActionExecContext context)
        {
            throw new NotImplementedException();
        }
    }
}
